package com.forhappy.light3ds8.server;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;

import com.forhappy.light3ds8.Led8Application;
import com.forhappy.light3ds8.shareprefrence.Config;

public class HttpUtils {
	private static final String TAG = "HttpUtils";
	public static class Result{
		public int code = 0;
		public String msg = "";
		public Result() {}
		public Result(String retJsonStr){
			JSONObject json;
			try {
				Log.d(TAG, "enter Result()");
				if(TextUtils.isEmpty(retJsonStr)){
					json = new JSONObject();
				} else {
					json = new JSONObject(retJsonStr);
				}
				if(json.has("result")){
					code = json.getInt("result");
				}
				//外界请求不一定按这个顺序走,有则取msg，没有则去全部
				if(json.has("msg")){
					msg = json.getString("msg");
				} else {
					msg = retJsonStr;
				}
			} catch (JSONException e) {
				//不一定为Json 字符串，直接取全部
				msg = retJsonStr;
			}
		}
		public Result(int code, String msg){
			this.code = code;
			this.msg = msg;
		}
		public boolean isSuccess(){
			return 0 == code;
		}
		@Override
		public String toString() {
			return "retCode:" + code + " msg:" + msg;
		}
	}

	public static interface PostCallBack{
		void onReceived(Result res);
	}

	public static void post(final String url,
			final HashMap<String, Object> params,
			final PostCallBack callback){
		new Thread(){
			@Override
			public void run() {
				Result res = post(url, params);
				callback.onReceived(res);
			};
		}.start();
	}
	public static Result post(String url, HashMap<String, Object> params) {
		Log.d(TAG, "enter HttpUtils::postr(url:" + url + ")");
		HttpPost httpPost = new HttpPost(url);

		params = addUserNameAndPassword(params);
		// 设置参数实体
		LinkedList<BasicNameValuePair> nameValuePaireList = new LinkedList<BasicNameValuePair>();
		if(null != params && !params.isEmpty()){
			for (Map.Entry<String, Object> entry : params.entrySet()) {
				Log.d(TAG, "params " + entry.getKey() + "=" + entry.getValue());
				BasicNameValuePair valuePair =
						new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue()));
				nameValuePaireList.add(valuePair);
			}
		}
//		httpPost.setParams(httpParams);
		try{
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePaireList));
		} catch(Exception e) {
			Log.e(TAG, e.toString(), e);
			return new Result(-1, "system err:" + e.toString());
		}

		// 获取HttpClient对象
		HttpClient httpClient = new DefaultHttpClient();
		// 连接超时
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		// 请求超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
		try {
			Log.d(TAG, "ready to exec httpPost!!");
			// 获取HttpResponse实例
			HttpResponse httpResp = httpClient.execute(httpPost);
			// 判断是够请求成功
			if (httpResp.getStatusLine().getStatusCode() == 200) {
				// 获取返回的数据
				String result = EntityUtils.toString(httpResp.getEntity(),
						"UTF-8");
				Log.i(TAG, "HttpPost方式请求成功，返回数据如下：");
				Log.i(TAG, result);
				return new Result(result);
			} else {
				Log.i(TAG, "HttpPost方式请求失败");
				return new Result(-1, "http code:" + httpResp.getStatusLine().getStatusCode());
			}
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, e.toString(), e);
			return new Result(-1, " system ConnectTimeoutException:" + e.toString());
		} catch (Exception e) {
			Log.e(TAG, e.toString(), e);
			return new Result(-1, " system err:" + e.toString());
		}
	}

	public static Result get(String url) {
		Log.d(TAG, "enter HttpUtils::postr(url:" + url + ")");
//		HttpPost httpPost = new HttpPost(url);
		HttpGet httpGet = new HttpGet(url);

		// 获取HttpClient对象
		HttpClient httpClient = new DefaultHttpClient();
		// 连接超时
		httpClient.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
		// 请求超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
		try {
			// 获取HttpResponse实例
			HttpResponse httpResp = httpClient.execute(httpGet);
			// 判断是够请求成功
			if (httpResp.getStatusLine().getStatusCode() == 200) {
				// 获取返回的数据
				String result = EntityUtils.toString(httpResp.getEntity(),
						"UTF-8");
				Log.i(TAG, "HttpGet方式请求成功，返回数据如下：");
				Log.i(TAG, result);
				return new Result(result);
			} else {
				Log.i(TAG, "HttpGet方式请求失败");
				return new Result(-1, "http code:" + httpResp.getStatusLine().getStatusCode());
			}
		} catch (ConnectTimeoutException e) {
			Log.e(TAG, e.toString(), e);
			return new Result(-1, " system ConnectTimeoutException:" + e.toString());
		} catch (Exception e) {
			return new Result(-1, " system err:" + e.toString());
		}
	}

	private static HashMap<String, Object> addUserNameAndPassword(HashMap<String, Object> params){
		Pair<String, String> namePasswd =  Config.getUserNamePassword(Led8Application.getLed8Application());
		if(null == params){
			params = new HashMap<String, Object>();
		}
		params.put("userName", namePasswd.first);
		params.put("password", namePasswd.second);
		return params;
	}
}
